package team.kirohuji.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import team.kirohuji.domain.SystemUser;
import team.kirohuji.message.entity.Email;
import team.kirohuji.service.EmailService;

@Controller
public class MessageNotificationController {

	@Resource
	private EmailService emailService;

	// 订阅事件
	@ResponseBody
	@RequestMapping(value = "/subscribeLoggerEmail", method = RequestMethod.POST)
	public int subscribeLoggerEmail(HttpSession session) {
		SystemUser sysUser = (SystemUser) session.getAttribute("user");
		List<Email> emails = emailService.queryAllByUserId(sysUser.getId());
		Iterator<Email> it = emails.iterator();
		while (it.hasNext()) {
			Email email = it.next();
			email.setIsSubscribe(1);
			emailService.update(email);
		}
		return 0;
	}

	// 订阅事件
	@ResponseBody
	@RequestMapping(value = "/addEmail", method = RequestMethod.POST)
	public int addEmail(HttpSession session, String receiveEmail) {
		List<Email> emails = new ArrayList<Email>();
		SystemUser sysUser = (SystemUser) session.getAttribute("user");
		emails = emailService.queryAllByUserId(sysUser.getId());
		if (emails.isEmpty()) {
			Email email = new Email();
			email.setReceiveEmail(receiveEmail);
			email.setUserId(sysUser.getId());
			emailService.save(email);
		} else {
			Email email = new Email();
			email.setEmailId(emails.get(0).getEmailId());
			email.setReceiveEmail(receiveEmail);
			email.setUserId(sysUser.getId());
			emailService.update(email);
		}
		return 0;
	}

	// 获取我的邮件
	@ResponseBody
	@RequestMapping(value = "/getMyEmail", method = RequestMethod.GET)
	public List<Email> getMyEmail(HttpSession session) {
		List<Email> emails = new ArrayList<Email>();
		SystemUser sysUser = (SystemUser) session.getAttribute("user");
		emails = emailService.queryAllByUserId(sysUser.getId());
		emails.forEach(System.out::println);
		return emails;
	}

}
